package com.cykj.order.controller;

/**
 * @BelongsProject: Cykj-Order-System
 * @BelongsPackage: com.cykj.order.controller
 * @Author: cwx
 * @CreateTime: 2025/9/4 12:09
 * @Description:
 * @Version: 1.0
 */

import com.cykj.common.core.web.controller.BaseController;
import com.cykj.common.core.web.domain.AjaxResult;

import com.cykj.order.domain.dto.AlipayPageReqDTO;
import com.cykj.order.domain.dto.OrderCreateReqDTO;
import com.cykj.order.service.OrderBusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 订单业务控制器（创建订单、支付相关）
 */
@RestController
@RequestMapping("/business")
public class OrderBusinessController extends BaseController {

    @Autowired
    private OrderBusinessService orderBusinessService;

    /**
     * 1. 创建订单接口（前端create.vue调用）
     */
    @PostMapping("/create")
    public AjaxResult createOrder(@Validated @RequestBody OrderCreateReqDTO reqDTO) {
        Long orderId = orderBusinessService.createOrder(reqDTO);
        return AjaxResult.success("订单创建成功", orderId);
    }

    /**
     * 2. 生成支付宝支付页面（前端payment.vue调用）
     * @return 支付宝支付HTML表单
     */
    @PostMapping("/alipay/page")
    public AjaxResult generateAlipayPage(@Validated @RequestBody AlipayPageReqDTO reqDTO) {
        String alipayHtml = orderBusinessService.generateAlipayPage(reqDTO);
        return AjaxResult.success(alipayHtml);
    }

    /**
     * 3. 支付宝支付回调接口（支付宝沙箱调用）

     */
    @PostMapping("/alipay/notify")
    public String handleAlipayNotify(HttpServletRequest request) {
        // 提取支付宝回调参数（request.getParameterMap）
        Map<String, String> paramMap = new HashMap<>();
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            paramMap.put(name, request.getParameter(name));
        }
        // 调用服务处理回调
        return orderBusinessService.handleAlipayNotify(paramMap);
    }
}
